package com.stn.zjx.givingtreasure.base;


import android.Manifest;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;


import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.set.PasswordSetActivity;
import com.stn.zjx.givingtreasure.broadcastreceiver.NetWorkChangeBroadcastreceiver;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.utils.LanguageUtils;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.widget.LoadingDialog;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxKeyboardTool;
import com.vondear.rxtools.view.RxToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import xyz.bboylin.universialtoast.UniversalToast;

/**
 * Created by 朱俊鑫 on 2018
 * 基础抽象UI界面
 * @author 朱俊鑫
 * @since 2018-3
 * @see AppCompatActivity
 * @property mSwipeBackHelper 手势返回帮助类
 * @property netWorkChangeBroadcastreceiver 监听网络变化广播
 * @property  REQUEST_PERMISSION 申请必要权限请求代码
 * @property  REQUEST_PERMISSION_OVERLAY 申请可显示app应用上层窗口权限请求代码
 * @
 */
public abstract class BaseActivity extends AppCompatActivity implements BGASwipeBackHelper.Delegate{
    /** 判断是否是快速点击 */
    private static long lastClickTime;
    //手势返回帮助类
    public BGASwipeBackHelper mSwipeBackHelper;
    //监听网络变化广播
    public NetWorkChangeBroadcastreceiver netWorkChangeBroadcastreceiver;
    //申请必要权限请求代码
    public final int REQUEST_PERMISSION=4404;
    //申请可显示app应用上层窗口权限请求代码
    public final int REQUEST_PERMISSION_OVERLAY=4405;
    public LoadingDialog loadingDialog=null;
    public boolean isLoading=false;
    public String extraData="";
    /**  被创建时，触发  */
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
         initSwipeBackFinish();
        String mode= LanguageUtils.getLanguageMode(this);
        LanguageUtils.switchLanguage(this,mode);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        netWorkChangeBroadcastreceiver= NetWorkChangeBroadcastreceiver.initNetWorkChangeBroadCastReceiver(this);
     //   methodRequiresTwoPermission();
        initLoadingDialog();
        StatusBarUtil.setImmersiveStatusBar(this,true);
        initStatusBarColor(false);
        RxActivityTool.addActivity(this);
    }

    public void initLoadingDialog(){
         loadingDialog=new LoadingDialog(this);
    }
    public void showLoading(){
         synchronized (BaseActivity.class){
             if(!isLoading&&!isFinishing()){
                 isLoading=true;
                 loadingDialog.show();
             }
         }

    }
    public void dissmissLoading(){
        if(!isFinishing()){
            loadingDialog.dismiss();
            isLoading=false;
        }
    }

    public void showToast(String content){
        RxToast.custom(this,content,null, getResources().getColor(R.color.white),getResources().getColor(R.color.font_black),Toast.LENGTH_SHORT,false,true).show();
    }

    public void showToast1(String content,int gravity,int type,int x,int y){
        switch (type){
            case 0:
                UniversalToast.makeText(this,content,UniversalToast.LENGTH_SHORT)
                        .setGravity(gravity,0,0)
                      .show();
                break;
            case 1:
                UniversalToast.makeText(this,content,UniversalToast.LENGTH_SHORT)
                        .setGravity(gravity,0,0)
                       .showSuccess();
                break;
            case 2:
                UniversalToast.makeText(this,content,UniversalToast.LENGTH_SHORT)
                        .setGravity(gravity,0,0)
                        .showError();
                break;
            case 3:
                UniversalToast.makeText(this,content,UniversalToast.LENGTH_SHORT)
                        .setGravity(gravity,0,0)
                        .showWarning();
                break;
        }

    }

    /**  被创建时之后，开始执行  */
    @Override
    protected void onStart() {
        super.onStart();

    }
    /**
     * @param  netWorkEvent 网络状态事件
     * 订阅,监听网络状态事件
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NetworkEvent(NetWorkEvent netWorkEvent){
        //网络状态回调，主线程
        networkStatus(netWorkEvent);
    }

    /**
     *
     * @param colorResId RBG颜色值 #FFFFFF等
     * 初始化状态栏颜色
     */
    //初始化状态栏颜色
    public void initStatusBarColor(int colorResId){
              SystemBarTintManager manager=new SystemBarTintManager(this);
               manager.setStatusBarTintEnabled(true);
               manager.setStatusBarTintColor(ActivityCompat.getColor(this,colorResId));
    }

    /**
     *
     * @param isTranslucent 是否设置状态栏为全透明
     * 设置状态栏颜色是否为透明
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void initStatusBarColor(boolean isTranslucent){
        Window window=getWindow();
         if(isTranslucent){
             window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
             window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
             window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                 window.setStatusBarColor(Color.TRANSPARENT);
             }
         }else{
             SystemBarTintManager manager=new SystemBarTintManager(this);
             manager.setStatusBarTintEnabled(true);
             manager.setStatusBarTintColor(android.R.color.transparent);


         }
    }


    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);
        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。
        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否开启手滑返回
     */
    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    /**
     * @param slideOffset 滑动迟滞
     * 监听滑动界面差值
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {

    }
    /**
     *
     * 监听滑动取消
     */
    @Override
    public void onSwipeBackLayoutCancel() {

    }
    /**
     *
     * 监听滑动执行
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        //滑动执行
        mSwipeBackHelper.swipeBackward();
    }

    /**
     *
     * 回调，网络改变状态
     */
    //网络改变状态
    public  abstract void networkStatus(NetWorkEvent netWorkEvent);

    /**
     *
     * 监听，按键返回
     */
    @Override
    public void onBackPressed() {
       //  正在滑动返回的时候取消返回按钮事件
        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        SoftInputUtils.closedSoftInput(this);

    }
    /**
     *
     * 界面销毁
     */
    @Override
    protected void onDestroy() {
        if(loadingDialog!=null){
            loadingDialog.dismiss();
        }
        super.onDestroy();
        //注销监听事件
        EventBus.getDefault().unregister(this);
        //注销监听网络状态广播
        if(netWorkChangeBroadcastreceiver!=null){
            unregisterReceiver(netWorkChangeBroadcastreceiver);
        }
        SoftInputUtils.closedSoftInput(this);

    }

    /**
     *
     * @param requestCode 请求权限代码
     * @param permissions  请求权限，字符串数组
     * @param grantResults 请求权限是否完成，状态数组
     */
  //请求权限返回结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 发送请求权限
     */
    @AfterPermissionGranted(REQUEST_PERMISSION)
    public void methodRequiresTwoPermission() {
        //相机，存储，定位，网络状态
        String[] perms = {Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.RECORD_AUDIO
        };
        //是否有以上权限
        if (EasyPermissions.hasPermissions(this, perms)) {

        } else {
            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc),
                    REQUEST_PERMISSION, perms);
        }

    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == REQUEST_PERMISSION) {
//            String text = Settings.canDrawOverlays(this) ? getString(R.string.already_perssion_popu) :getString(R.string.request_perssion_popu);
//            UniversalToast.makeText(getApplicationContext(), text, UniversalToast.LENGTH_SHORT).show();
//        }
//    }


    public abstract void initComponent();


   //防止重复点击导致
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 300) {

            return true;
        }
        lastClickTime = time;
        return false;

    }
    /** 判断触摸时间派发间隔 */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void finish() {
        super.finish();
      SoftInputUtils.closedSoftInput(this);
    }
}
